package com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.handlers;


import com.xiaomaoguai.fcp.pre.kepler.router.rpc.options.ServerOptions;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.channelInitializer.NettyChannelInitializer;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.enums.Protocol;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.core.NettyContext;

import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.ReadTimeoutHandler;

import java.util.concurrent.TimeUnit;

public class NettyServletChannelInitializer extends NettyChannelInitializer {

	private NettyContext servletContext;

	public NettyServletChannelInitializer(Protocol protocol, Integer timeout, Integer nProcessors, NettyContext servletContext) {
		super(protocol, timeout, nProcessors);
		this.servletContext = servletContext;
	}

	@Override
	public void initChannel(SocketChannel ch) throws Exception {
		ch.pipeline()
				.addLast("kepler-servlet-readTimeout", new ReadTimeoutHandler(timeout, TimeUnit.MILLISECONDS))
				.addLast("kepler-servlet-decode", new HttpServerCodec(1024 * 4, 1024 * 8, 1024 * 16, false))// HTTP 服务的解码器
				.addLast("kepler-servlet-aggregator", new HttpObjectAggregator(ServerOptions.MAX_PACKET_SIZE))// HTTP 消息的合并处理
				.addLast(defaultEventExecutorGroup, "kepler-servlet-handler", new RequestDispatcherHandler(servletContext)); // 逻辑处理
	}
}
